package networkinterface;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @author Michael & Pierre
 */
/**
 * Thread which listens the network when the user is connected
 */
public class ListeningThread extends Thread {
	
	private static JavaNI javaNI;
	private int port;
	/**
	 * Socket used to listen the network
	 */
	private static DatagramSocket myListeningSock;
	
	/**
	 * @param javaNI Network Interface of the chat system
	 * @param port Local port where the messages are received
	 */
	public ListeningThread(JavaNI javaNI, int port) {
		ListeningThread.javaNI = javaNI;
		this.port = port;
	}
	
	public void run() {
		DatagramPacket myPacket;
		byte[] recvData;

		try {
			
			myListeningSock = new DatagramSocket(port);
			int size = myListeningSock.getReceiveBufferSize(); //récupère taille buffer réception
			
			while(!interrupted()) {
				recvData = new byte[size];
				myPacket = new DatagramPacket(recvData, recvData.length);
				myListeningSock.receive(myPacket);
				
				javaNI.packetRcvd(myPacket);
			}
			myListeningSock.close();
		} catch (SocketException e) {
			if (!interrupted()) {
				e.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * method which interrupts the thread and closes the socket
	 */
	public void interrupt(){
	     super.interrupt();  
	     myListeningSock.close();
	   }
}
